"""
|===== Conference Bot Plugin ============
|= Timer Events
|===== By: ==============================
|= Patrick Kennedy
|===== Current Version: =================
|= 1.0
|===== Description: =========================================
|= These events will run at regular intervals.
|===== Additional Comments: =================================
|= 
|============================================================"""

from utils import isplugin, getjid, getdisplayname
from ini import userlist

global watch_list
watch_list = userlist[getjid("watched")]

def timer_statuscheck(bot):
	watch_list = userlist[getjid("watched")]
	roster = bot.getRoster()
	for jid in bot.getRoster():
		jid = getjid(jid)
		if jid in roster:
			jidStatus = bot.getJidStatus(jid).items()
		for user,(status,display) in jidStatus:
			user = getjid(user)
			last_status = userlist[user]["jabberstatus"]
			if not jidStatus:
				userlist[user]["jabberstatus"] = "offline"
				if watch_list.has_key(user):
					sub_watched(bot, user, "offline", last_status)
				break
			if [(unicode(jid),message) for (jid,(status,message)) in jidStatus if status in ["online","chat"]]:
				userlist[user]["jabberstatus"] = status
			elif [(unicode(jid),message) for (jid,(status,message)) in jidStatus if status in [u"away",u"dnd",u"xa"]]:
				userlist[user]["jabberstatus"] = status
			if status and watch_list.has_key(user) and status != userlist[user]["jabberstatus"]:
				sub_watched(bot, user, status, last_status)
			break

			
def sub_watched(bot, user, status, last_status):
	for watcher in watch_list[user]:
		if status in ["online","chat"] and last_status not in ["online","chat"]:
			if last_status == "offline":
				bot.msg(watcher, "%s is now 'Online'." % getdisplayname(user))
			else:
				bot.msg(watcher, "%s is now 'Available'." % getdisplayname(user))
		elif status == "dnd":
			bot.msg(watcher, "%s is now 'Busy'." % getdisplayname(user))
		elif status in ["away","xa"]:
			bot.msg(watcher, "%s is now 'Idle'." % getdisplayname(user))
		elif status == "offline":
			bot.msg(watcher, "%s is now 'Offline'." % getdisplayname(user))
	userlist[user]["jabberstatus"] = status

def init(bot):
	if isplugin("watch"):
		bot.addTimer(5, timer_statuscheck, type = "seconds")
